﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using Tfs.OnTheRoad.ViewModel;

namespace Tfs.OnTheRoad.Controls
{
    /// <summary>
    /// Reusable WorkItems Chart Control
    /// DataContext should be a WorkItemsChartViewModel
    /// </summary>
	public partial class WorkItemsOverviewChartControl : UserControl
	{        
        public WorkItemsOverviewChartControl()
		{
			// Required to initialize variables
			InitializeComponent();
            DrillDownEnabled = true; 
		}

        void ViewModel_ChartDataPrepared(object sender, EventArgs e)
        {
            this.LoadChart(ViewModel.WorkItemsSummary);
        }

        private WorkItemsChartViewModel ViewModel;
        public void LoadChart(WorkItemsSummaryList chartData)
        {
            StackedColumnSeries series = new StackedColumnSeries();
            series.SelectionMode = SeriesSelectionMode.Single;
            series.SelectionChanged += new SelectionChangedEventHandler(series_SelectionChanged);
            workItemsChart.Series.Clear();
            workItemsChart.Series.Add(series);
            foreach (var item in chartData)
            {
                SeriesDefinition columnSeries = new SeriesDefinition();
                columnSeries.ItemsSource = item.Types;
                columnSeries.Title = item.State;
                columnSeries.DependentValuePath = "Count";
                columnSeries.IndependentValuePath = "Type";
                series.SeriesDefinitions.Add(columnSeries);
            }
            workItemsChart.Visibility = System.Windows.Visibility.Visible;
        }

        public bool DrillDownEnabled
        {
            get;
            set;
        }

        void series_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(DrillDownEnabled)
            {
                Tfs.OnTheRoad.Commands.NavigateToWorkItemsOverviewCommand cmd = new Commands.NavigateToWorkItemsOverviewCommand();
                cmd.Execute(e);
            }
        }

        private void ChartControl_Loaded(object sender, RoutedEventArgs e)
        {
            ViewModel = this.DataContext as WorkItemsChartViewModel;
            ViewModel.ChartDataPrepared += new EventHandler(ViewModel_ChartDataPrepared);  
        }
	}
}